package jmine.tec.benchmark;

import java.io.Serializable;
import java.lang.reflect.Method;

import jmine.tec.proxy.chain.ChainElement;
import jmine.tec.proxy.chain.InvocationChain;
import jmine.tec.utils.debug.TimerGroup;
import jmine.tec.utils.debug.impl.DebugRuntimeFactory;

/**
 * {@link ChainElement} que conta o tempo acumulado gasto em cada metodo. O {@link #toString()} deste metodo devolve uma tabela separada por
 * tabs
 * 
 * @author takeshi
 */
public class AccumulatedMethodTimingChainElement implements ChainElement, Serializable {

    /**
     * @param chain o {@link InvocationChain}
     * @throws Throwable e
     * @return object
     */
    public Object aroundInvoke(final InvocationChain chain) throws Throwable {
        final Method targetMethod = chain.getInvokingMethod();
        final TimerGroup timer = DebugRuntimeFactory.getInstance().getOrCreateTimer(targetMethod.getDeclaringClass().getName());
        timer.start(targetMethod.getName());
        try {
            return chain.proceed();
        } finally {
            timer.stop(targetMethod.getName());
        }
    }

}
